package com.alander.nexusgo.im.netty;

import cn.hutool.json.JSONUtil;
import com.alander.nexusgo.im.constants.ImConstants;
import com.alander.nexusgo.im.constants.ImMsgCodeEnum;
import com.alander.nexusgo.im.model.dto.ImMsg;
import com.alander.nexusgo.im.model.dto.ImMsgBody;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 群聊消息处理器
 */
public class ChatRoomHandler extends SimpleChannelInboundHandler<ImMsg> {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(ChatRoomHandler.class);
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ImMsg msg) throws Exception {
        // 只处理业务消息
        if (msg.getCode() == ImMsgCodeEnum.IM_BIZ_MSG.getCode()) {
            handleChatRoomMessage(ctx, msg);
        } else {
            // 将消息传递给下一个处理器
            ctx.fireChannelRead(msg);
        }
    }
    
    /**
     * 处理群聊消息
     * @param ctx 通道上下文
     * @param msg 消息
     */
    private void handleChatRoomMessage(ChannelHandlerContext ctx, ImMsg msg) {
        try {
            // 解析消息体
            String bodyJson = new String(msg.getBody());
            ImMsgBody msgBody = JSONUtil.toBean(bodyJson, ImMsgBody.class);
            
            // 获取群组ID（使用bizCode作为群组ID）
            int roomId = msgBody.getBizCode();
            
            // 获取群组通道组
            ChannelGroup roomGroup = ImConnectionManager.getChatRoomGroup(roomId);
            if (roomGroup == null || roomGroup.size() <= 0) {
                LOGGER.warn("群组不存在或为空: roomId={}", roomId);
                return;
            }
            
            // 构造返回消息
            ImMsg response = new ImMsg();
            response.setMagic(ImConstants.DEFAULT_MAGIC);
            response.setCode(ImMsgCodeEnum.IM_BIZ_MSG.getCode());
            
            // 重新构造消息体
            ImMsgBody responseBody = new ImMsgBody();
            responseBody.setAppId(msgBody.getAppId());
            responseBody.setUserId(msgBody.getUserId()); // 设置发送者ID
            responseBody.setBizCode(roomId); // 设置群组ID
            responseBody.setMsgId(msgBody.getMsgId());
            responseBody.setData(msgBody.getData());
            
            String responseBodyJson = JSONUtil.toJsonStr(responseBody);
            byte[] responseBodyBytes = responseBodyJson.getBytes();
            
            response.setLen(responseBodyBytes.length);
            response.setBody(responseBodyBytes);
            
            // 广播消息给群组中的所有用户（除了发送者自己）
            roomGroup.writeAndFlush(response, channel -> !channel.equals(ctx.channel()));
            
            LOGGER.info("群聊消息发送成功: roomId={} sender={} msgId={}", roomId, msgBody.getUserId(), msgBody.getMsgId());
        } catch (Exception e) {
            LOGGER.error("处理群聊消息时发生错误", e);
        }
    }
}